package com.umakr.ax.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 *
 * @author ~scl
 * @date 2017/5/24
 */
public class RestfulUtil {
    protected static final Log logger = LogFactory.getLog(RestfulUtil.class);
    public static String getMessage(String targetURL){
        String result = "";
        try {

            URL restServiceURL = new URL(targetURL);

            HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Accept", "application/json");

            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException("HTTP GET Request Failed with Error code : "
                        + httpConnection.getResponseCode());
            }

            BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
                    (httpConnection.getInputStream())));

            String output;

            while ((output = responseBuffer.readLine()) != null) {
                result += output;
            }

            httpConnection.disconnect();

        } catch (MalformedURLException e) {

            logger.error(e);

        } catch (IOException e) {

            logger.error(e);
        }
        return result;
    }

    public static String postMessage(String targetURL,String inputJson){
        String result = "";
        try {
            URL targetUrl = new URL(targetURL);

            HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Content-Type", "application/json");

            OutputStream outputStream = httpConnection.getOutputStream();
            outputStream.write(inputJson.getBytes());
            outputStream.flush();

            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + httpConnection.getResponseCode());
            }

            BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
                    (httpConnection.getInputStream())));

            String output ;
            while ((output = responseBuffer.readLine()) != null) {
                result += output;
            }

            httpConnection.disconnect();

        } catch (MalformedURLException e) {

            logger.error(e);

        } catch (IOException e) {

            logger.error(e);

        }
        return result;
    }

}
